﻿using AutoMapper;
using Domain.Material_Management;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules.GroupInventory;
using ReturnValue;
using System.Transactions;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Production_Modules.GroupInventory
{
    public class AddGroupOutHander : IRequestHandler<AddGroupOutCommand, ApiResult<int>>
    {
        private readonly IRepository<GroupOutInModel> groupOutInRepo;
        private readonly IRepository<GroupInventoryModel> groupInventoryRepo;
        private readonly IRepository<MaterialGroupModel> materialGroupRepo;
        public AddGroupOutHander(IRepository<GroupOutInModel> groupOutInRepo, IRepository<GroupInventoryModel> groupInventoryRepo, IRepository<MaterialGroupModel> materialGroupRepo)
        {
            this.groupOutInRepo = groupOutInRepo;
            this.groupInventoryRepo = groupInventoryRepo;
            this.materialGroupRepo = materialGroupRepo;
        }
        /// <summary>
        /// 群组出库
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddGroupOutCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            var outt = groupOutInRepo.GetAll().Where(x => x.OutInCode == request.OutInCode).FirstOrDefault();
            if (outt != null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "群组出库编码已存在,无法进行出库";
                return await Task.FromResult(result);
            }
            else
            {
                GroupOutInModel GroupOut = new GroupOutInModel()
                {
                    Id = YitIdHelper.NextId(),
                    OutInCode = request.OutInCode,
                    OutIn = OutInEnum.出库,
                    OutInCount = request.OutInCount,
                    MaterialGroupId = request.MaterialGroupId,
                    CreateTime = DateTime.Now,
                    CreaterPeople = request.CreaterPeople,
                    IsDel = false
                };
                //出库的产品物料
                var materialGroup = await materialGroupRepo.GetValue(request.MaterialGroupId);
                //当前出库的物料库存
                var groupInventory = groupInventoryRepo.GetAll().FirstOrDefault(x => x.MaterialGroupId == request.MaterialGroupId);
                if (GroupOut.OutInCount > groupInventory.CurrentInventory)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "群组库存量不足,无法出库";
                    return await Task.FromResult(result);
                }
                materialGroup.MaterialGroupCount = materialGroup.MaterialGroupCount + request.OutInCount;
                groupInventory.CurrentInventory = groupInventory.CurrentInventory - (int)request.OutInCount;
                int i1 = 0;
                int i2 = 0;
                int i3 = 0;
                using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        i1 = await groupOutInRepo.AddAsync(GroupOut);
                        i2 = await materialGroupRepo.UpdateAsync(materialGroup);
                        i3 = await groupInventoryRepo.UpdateAsync(groupInventory);
                        tran.Complete();
                    }
                    catch (Exception ex)
                    {

                        throw ex;
                    }
                }
                if (i1 > 0 && i2 > 0&&i3>0)
                {
                    result.Code = StatusCode.Success;
                    result.Message = "已成功出库";
                    return await Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "出库失败";
                    return await Task.FromResult(result);
                }
            }
        }
    }
}
